using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WorkFlowCore.BusinessDemo.Web.Data;
using WorkFlowCore.BusinessDemo.Web.Entities;
using WorkFlowCore.BusinessDemo.Web.Models;

namespace WorkFlowCore.BusinessDemo.Web.Controllers
{
    public class UserController : BaseController
    {
        private readonly BusinessDemoDbContext _context;
        private const int DefaultPageSize = 10;

        public UserController(BusinessDemoDbContext context)
        {
            _context = context;
        }

        // 用户列表(支持分页和查询)
        public IActionResult Index(int pageIndex = 1, int pageSize = DefaultPageSize, 
            string employeeNumber = null, string name = null, int? organizationId = null)
        {
            var query = _context.Users
                .Include(u => u.UserRoles)
                .ThenInclude(ur => ur.Role)
                .Include(u => u.Organization)
                .AsQueryable();

            // 查询条件
            if (!string.IsNullOrEmpty(employeeNumber))
            {
                query = query.Where(u => u.EmployeeNumber.Contains(employeeNumber));
            }
            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(u => u.Name.Contains(name));
            }
            if (organizationId.HasValue)
            {
                query = query.Where(u => u.OrganizationId == organizationId);
            }

            // 排序
            query = query.OrderBy(u => u.Name);

            // 分页
            var totalCount = query.Count();
            var items = query
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Select(u => new UserListViewModel
                {
                    Id = u.Id,
                    Name = u.Name,
                    EmployeeNumber = u.EmployeeNumber,
                    Phone = u.Phone,
                    Email = u.Email,
                    Gender = u.Gender,
                    BirthDate = u.BirthDate,
                    Hometown = u.Hometown,
                    UpdateTime = u.UpdateTime,
                    Roles = u.UserRoles.Select(ur => new RoleInfo
                    {
                        Id = ur.Role.Id,
                        Name = ur.Role.Name
                    }).ToList(),
                    OrganizationId = u.OrganizationId,
                    OrganizationName = u.Organization != null ? u.Organization.Name : null
                })
                .ToList();

            var result = new PagedResult<UserListViewModel>
            {
                TotalCount = totalCount,
                PageIndex = pageIndex,
                PageSize = pageSize,
                Items = items
            };

            return View(result);
        }

        // 用户详情
        public IActionResult Details(int id)
        {
            var user = _context.Users
                .Include(u => u.UserRoles)
                .ThenInclude(ur => ur.Role)
                .FirstOrDefault(u => u.Id == id);
            
            if (user == null)
            {
                return NotFound();
            }

            var viewModel = new UserDetailViewModel
            {
                Id = user.Id,
                Name = user.Name,
                EmployeeNumber = user.EmployeeNumber,
                Phone = user.Phone,
                Email = user.Email,
                Gender = user.Gender,
                BirthDate = user.BirthDate,
                Hometown = user.Hometown,
                Roles = user.UserRoles.Select(ur => new UserDetailViewModel.RoleInfo
                {
                    Id = ur.Role.Id,
                    Name = ur.Role.Name
                }).ToList()
            };

            return View(viewModel);
        }

        // 添加用户 - GET
        public IActionResult Create()
        {
            return View();
        }

        // 添加用户 - POST
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(UserCreateViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                {
                    Name = viewModel.Name,
                    EmployeeNumber = viewModel.EmployeeNumber,
                    Phone = viewModel.Phone,
                    Email = viewModel.Email,
                    Gender = viewModel.Gender,
                    BirthDate = viewModel.BirthDate,
                    Hometown = viewModel.Hometown,
                    CreateTime = DateTime.Now,
                    Creator = CurrentEmployeeNumber, // 使用工号作为创建人
                    UpdateTime = DateTime.Now,
                    Updater = CurrentEmployeeNumber // 使用工号作为更新人
                };

                _context.Users.Add(user);
                _context.SaveChanges();

                return RedirectToAction(nameof(Index));
            }

            return View(viewModel);
        }

        // 更新用户 - GET
        public IActionResult Edit(int id)
        {
            var user = _context.Users.Find(id);
            if (user == null)
            {
                return NotFound();
            }

            var viewModel = new UserUpdateViewModel
            {
                Id = user.Id,
                Name = user.Name,
                Phone = user.Phone,
                Email = user.Email,
                Gender = user.Gender,
                BirthDate = user.BirthDate,
                Hometown = user.Hometown
            };

            return View(viewModel);
        }

        // 更新用户 - POST
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int id, UserUpdateViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                var user = _context.Users.Find(id);
                if (user == null)
                {
                    return NotFound();
                }

                user.Name = viewModel.Name;
                user.Phone = viewModel.Phone;
                user.Email = viewModel.Email;
                user.Gender = viewModel.Gender;
                user.BirthDate = viewModel.BirthDate;
                user.Hometown = viewModel.Hometown;
                user.UpdateTime = DateTime.Now;
                user.Updater = CurrentEmployeeNumber; // 使用工号作为更新人

                _context.Update(user);
                _context.SaveChanges();

                return RedirectToAction(nameof(Index));
            }

            return View(viewModel);
        }

        // 分配角色 - GET
        public IActionResult AssignRoles(int id)
        {
            var user = _context.Users
                .Include(u => u.UserRoles)
                .FirstOrDefault(u => u.Id == id);
            
            if (user == null)
            {
                return NotFound();
            }

            var allRoles = _context.Roles.ToList();
            var userRoleIds = user.UserRoles.Select(ur => ur.RoleId).ToList();

            var viewModel = new AssignRolesViewModel
            {
                UserId = user.Id,
                UserName = user.Name,
                AvailableRoles = allRoles.Select(r => new AssignRolesViewModel.RoleCheckboxItem
                {
                    RoleId = r.Id,
                    RoleName = r.Name,
                    IsSelected = userRoleIds.Contains(r.Id)
                }).ToList()
            };

            return View(viewModel);
        }

        // 分配角色 - POST
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult AssignRoles(AssignRolesViewModel viewModel)
        {
            var user = _context.Users
                .Include(u => u.UserRoles)
                .FirstOrDefault(u => u.Id == viewModel.UserId);
            
            if (user == null)
            {
                return NotFound();
            }

            // 更新用户角色
            var selectedRoleIds = viewModel.AvailableRoles?
                .Where(r => r.IsSelected)
                .Select(r => r.RoleId)
                .ToList() ?? new List<int>();

            // 移除未选中的角色
            var rolesToRemove = user.UserRoles
                .Where(ur => !selectedRoleIds.Contains(ur.RoleId))
                .ToList();
            
            foreach (var role in rolesToRemove)
            {
                user.UserRoles.Remove(role);
            }

            // 添加新选中的角色
            var existingRoleIds = user.UserRoles.Select(ur => ur.RoleId).ToList();
            var rolesToAdd = selectedRoleIds
                .Where(id => !existingRoleIds.Contains(id))
                .Select(id => new UserRole { UserId = user.Id, RoleId = id })
                .ToList();
            
            foreach (var role in rolesToAdd)
            {
                user.UserRoles.Add(role);
            }

            try 
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                // 记录错误日志
                Console.WriteLine($"保存角色分配失败: {ex.Message}");
                ModelState.AddModelError("", "保存角色分配失败，请重试");
                return View(viewModel);
            }

            return RedirectToAction(nameof(Details), new { id = user.Id });
        }

        // 分配组织 - GET
        public IActionResult AssignOrganization(int organizationId)
        {
            var organization = _context.Organizations.Find(organizationId);
            if (organization == null)
            {
                return NotFound();
            }

            var allUsers = _context.Users.ToList();
            var orgUsers = _context.Users.Where(u => u.OrganizationId == organizationId).ToList();

            var viewModel = new AssignOrganizationViewModel
            {
                OrganizationId = organization.Id,
                OrganizationName = organization.Name,
                AvailableUsers = allUsers.Select(u => new AssignOrganizationViewModel.UserCheckboxItem
                {
                    UserId = u.Id,
                    UserName = u.Name,
                    IsSelected = orgUsers.Any(ou => ou.Id == u.Id)
                }).ToList()
            };

            return View(viewModel);
        }

        // 分配组织 - POST
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult AssignOrganization(AssignOrganizationViewModel viewModel)
        {
            var organization = _context.Organizations.Find(viewModel.OrganizationId);
            if (organization == null)
            {
                return NotFound();
            }

            // 获取选中的用户ID
            var selectedUserIds = viewModel.AvailableUsers?
                .Where(u => u.IsSelected)
                .Select(u => u.UserId)
                .ToList() ?? new List<int>();

            // 更新用户组织关系
            var usersToUpdate = _context.Users
                .Where(u => selectedUserIds.Contains(u.Id) || u.OrganizationId == viewModel.OrganizationId)
                .ToList();

            foreach (var user in usersToUpdate)
            {
                // 如果用户被选中，则分配到当前组织
                // 如果用户未被选中但属于当前组织，则移除组织关系
                user.OrganizationId = selectedUserIds.Contains(user.Id) ? viewModel.OrganizationId : null;
            }

            try
            {
                _context.SaveChanges();
                TempData["SuccessMessage"] = "组织分配保存成功";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存组织分配失败: {ex.Message}");
                TempData["ErrorMessage"] = "保存组织分配失败，请重试";
                return View(viewModel);
            }

            return RedirectToAction("Index", "Organization");
        }
    }
}
